<?php
/**
 * 菜单逻辑模块
 * @author Paco
 * @date  2017-07-29
 */

namespace app\common\logic;

use arrayset\Arrayset;
use think\auth\Auth;
use think\Cache;

class MenuLogic
{
    private $menu_m;
    private $array_c;

    public function __construct()
    {
        $this->menu_m  = model("Menu");
        $this->array_c = new Arrayset();
    }

    /**
     * 后台菜单
     * @return [type] [description]
     */
    public function getAdminList()
    {
        $menu = session("adminmenu");

        //$menu = Cache::tag('menu')->get('adminmenu');
        if (!$menu) {

            $_menu = [];
            //取出菜单列表
            $menu = $this->getCatByType(0, 1);
          
            $auth = new Auth();
            foreach ($menu as $key => $v) {
                if ($auth->check($v['rule'], session('admin')["id"])) {
                    $_menu[] = $v;
                }
            }
            $menu = $this->array_c->getTree($_menu);
           
            $menu = $this->array_c->setArrayKey($menu);
            $menu = $this->array_c->getDeepTree($menu);
            session("adminmenu",$menu);
        }
        return $menu;
    }

    /**
     * 后台编辑菜单列表
     * @return [type] [description]
     */
    public function getAdminEditList()
    {
        $menu = $this->getMenus();
        return $this->array_c->getTree($menu);
    }

    /**
     *@todo 查找所有的菜单
     *@return array 菜单树数组
     */
    public function getMenus()
    {
        $menu = Cache::tag('menu')->get('allmenu');
        if (!$menu) {
            $menu = $this->menu_m->getMenu();
            if ($menu) {
                Cache::tag('menu')->set('allmenu', $menu);
            }
        }
        return $menu;
    }

    /**
     * 把菜单ID设成数组的key值
     * @param array $menu 菜单数组
     */
    public function setMenuKey($menu)
    {
        $arr = [];
        if ($menu) {
            foreach ($menu as $k => $v) {
                $arr[$v['id']] = $v;
            }
        }
        return $arr;
    }

    /**
     * 查找所有启用的菜单
     * @return fixed
     */
    public function getActiveMenu()
    {
        $menu = Cache::tag('menu')->get('active');

        if (!$menu) {
            $menu = $this->getMenus();
            if ($menu) {
                foreach ($menu as $key => $v) {
                    if (!$v['status']) {
                        unset($menu[$key]);
                    }
                }
                Cache::tag('menu')->set('active', $menu);
            }
        }
        return $menu;
    }

    /**
     * 根据ID取得menu数据
     * @param  int $id 菜单的ID
     * @return array     一条菜单记录
     */
    public function getMenuById($id)
    {
        $menu = $this->array_c->setArrayKey($this->getMenus());
        return isset($menu[$id]) ? $menu[$id] : false;
    }

    /**
     * 根据类别查找菜单
     * @param  int $type [1、后台菜单，2、PC菜单 3、微信菜单]
     * @param  boolean $active 为真时返回本类别启用的菜单，为假时所有本类别的菜单
     * @return array       返回类别的菜单
     */
    public function getCatByType($type = 1, $active = 1)
    {
        if ($active) {
            $menu = $this->getActiveMenu();
        } else {
            $menu = $this->getMenus();
        }

        if ($menu) {
            foreach ($menu as $key => $v) {
                if ($v['type'] != $type) {
                    unset($menu[$key]);
                }
            }
        }
        return $menu;
    }

    /**
     * 添加或更新菜单
     * @param  array $data 更新的数据
     * @return int    返回影响的行数或ID
     */
    public function saveMenu($data)
    {
        $where = false;
        if (isset($data['id'])) {
            $ids    = explode(",", $data['id']);
            $arr_id = [];

            //当更新状态时
            if (isset($data['status'])) {
                $menu = $this->getMenus();
                $menu = $this->array_c->setArrayKey($menu);

                //如果为开启状态，需判断父级是否是开启，若不是不能开启
                if ($data['status']) {
                    foreach ($ids as $v) {
                        if ($menu[$v]['pid']) {
                            if (!$menu[$menu[$v]['pid']]['status']) {
                                $arr['msg'] = "请先启用父类:" . $menu[$menu[$v]['pid']]['name'];
                                break;
                            }
                        }
                    }

                } else {

                    foreach ($ids as $val) {
                        foreach ($menu as $key => $v) {
                            if ($v['pid'] == $val) {
                                if ($v['status']) {
                                    $arr['msg'] = "请先关闭子类:" . $v['name'];
                                    break;
                                }
                            }
                        }
                    }
                }

                if (isset($arr['msg'])) {
                    return $arr;
                }
            }

            $where['id'] = ["in", $data['id']];
            unset($data['id']);
        }

        if ($arr['data']['id'] = $this->menu_m->saveMenu($data, $where)) {
            Cache::clear("menu");
            $arr['msg']    = "更新成功";
            $arr['status'] = 200;
        } else {
            $arr['msg'] = "更新失败";
        }
        return $arr;
    }

    /**
     * 删除菜单
     * @param  fixed $id  单个整型ID也可是逗号相连的字符串
     * @return [type]     [description]
     */
    public function delMenu($id)
    {
        if ($id) {
            $id = explode(",", $id);
             $menu = $this->getMenus();
            foreach ($id as $val) {
                //判断是否有子类
                if ($this->array_c->haveChild($val,$menu)) {
                    $arr['msg']    = "ID为" . $val . "的菜单下有子菜单，不能删除...";
                    $arr['status'] = 0;
                    return $arr;
                }
            }

            if ($this->menu_m->delMenu($id)) {
                Cache::clear("menu");
                $arr['msg']    = "删除成功";
                $arr['status'] = 200;
                return $arr;
            }

        } else {
            $arr['msg']    = "参数出错，请稍后再试...";
            $arr['status'] = 0;
            return $arr;
        }
    }

}
